package com.dave.gd.core.base.repository;

import java.io.Serializable;

import org.springframework.beans.BeansException;
import org.springframework.util.StringUtils;

import com.dave.gd.common.log.ILogger;
import com.dave.gd.common.log.LoggerFactory;
import com.dave.gd.common.util.spring.ApplicationContextUtil;
import com.dave.gd.core.base.entity.impl.AbstractBaseEntity;

public class RepositoryFactory {
    
    private static final ILogger LOG = LoggerFactory.getLogger(RepositoryFactory.class);
    
    public <T extends AbstractBaseEntity<I>, I extends Serializable> IBaseRepository<T, I> getRepository(
        Class<T> c) {
        IBaseRepository<T, I> rep = null;
        
        // 0. 从Spring上下文中获取
        String repositoryName = StringUtils.uncapitalize(c.getSimpleName() + "Repository");
        System.out.println(repositoryName);
        try {
            rep = ApplicationContextUtil.getBean(repositoryName);
            return rep;
        } catch (BeansException nb) {
            LOG.debug("Spring上下文中未配置仓库：" + repositoryName);
        }
        
        // 4. 获得默认工厂
        rep = this.getDefaultRepository(c);
        return rep;
    }
    
    protected <T extends AbstractBaseEntity<I>, I extends Serializable> IBaseRepository<T, I> getDefaultRepository(
        final Class<T> c) {
        IBaseRepository<T, I> result = ApplicationContextUtil.getBean("defaultRepository");
        result.setRepositoryClass(c);
        return result;
    }
    
}
